package com.behelpful.demo.quartz.invoker;

import com.behelpful.demo.quartz.entity.SystemJob;
import com.behelpful.demo.quartz.entity.TestRestInfo;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.fastjson.FastjsonMsgConvertor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Rest Url 调用执行的执行器（未实现,可选的）
 *
 * @author Alay
 * @date 2021-10-31 18:01
 * @since
 */
@Slf4j
@Service(value = "REST")
public class RestInvoker implements ITaskInvoker {

    /**
     * @param baseUrl （可选的）
     * @return
     * @see {https://okhttps.ejlchina.com/v3/configuration.html}
     */
    private HTTP http(String baseUrl) {
        return HTTP.builder()
                // 配置连接池 最小10个连接（不配置默认为 5）
                .config(builder -> builder.connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES)))
                .baseUrl(baseUrl)
                .addMsgConvertor(new FastjsonMsgConvertor())
                .build();
    }

    @Override
    public void doInvoke(SystemJob systemJob) {
        // 模拟数据库查询获取请求参数信息
        TestRestInfo testRestInfo = TestRestInfo.restInfoById(systemJob.getRestId());

        HttpResult httpResult = this.http(testRestInfo.getBaseUrl())
                .async(testRestInfo.getExecutePath())
                .bodyType(testRestInfo.getBodyType())
                .request(testRestInfo.getMethod())
                .getResult();

        if (httpResult.isSuccessful()) {
            log.info("REST 调用成功");
            TestResultBean resultBean = httpResult.getBody().toBean(TestResultBean.class);
        } else {
            log.info("REST 调用失败");
        }
    }


    /**
     * 仅仅是示例
     */
    @Data
    private static class TestResultBean {
        private String testString;
        private Integer testInt;
    }
}